import React, { useState } from 'react';
import { createPost } from '../api';
import { useParams, useNavigate } from 'react-router-dom';

const NewPost: React.FC = () => {
  const { topicId } = useParams();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleSubmit = async () => {
    if (!title.trim() || !content.trim()) {
      alert('标题和内容不能为空');
      return;
    }
    setLoading(true);
    try {
      await createPost({ title, content, topicId: topicId! });
      navigate(`/topics/${topicId}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 500, margin: '60px auto', background: '#fff', borderRadius: 10, boxShadow: '0 2px 16px 0 rgba(0,0,0,0.07)', padding: 32 }}>
      <h2 style={{ marginTop: 0 }}>创建新帖子</h2>
      <input
        value={title}
        onChange={e => setTitle(e.target.value)}
        placeholder="帖子标题"
        style={{ width: '100%', fontSize: 16, padding: '8px 10px', borderRadius: 6, border: '1px solid #ddd', marginBottom: 16 }}
      />
      <textarea
        value={content}
        onChange={e => setContent(e.target.value)}
        placeholder="帖子内容"
        style={{ width: '100%', fontSize: 15, padding: '8px 10px', borderRadius: 6, border: '1px solid #ddd', minHeight: 100, resize: 'vertical', marginBottom: 24 }}
      />
      <div style={{ textAlign: 'right' }}>
        <button onClick={() => navigate(-1)} style={{ marginRight: 12, background: '#e5e7eb', color: '#222', borderRadius: 8, minWidth: 70 }}>取消</button>
        <button onClick={handleSubmit} disabled={loading} style={{ background: '#222', color: '#fff', borderRadius: 8, minWidth: 70, fontWeight: 600 }}>发布</button>
      </div>
    </div>
  );
};

export default NewPost;
